import request from '@/utils/request'

// 查询文件详情
export function getFile(fileId) {
  return request({
    url: '/system/file/' + fileId,
    method: 'get'
  })
}

// 将 base64 字符串转换为 Blob 对象
export const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);
    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
  return new Blob(byteArrays, { type: contentType });
};

// 下载文件函数
export const downloadFile = (b64Data, suffix, fileName) => {
  const content = getContentTypeFromFile(suffix);
  const blob = b64toBlob(b64Data, content);
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(url);
};

function getContentTypeFromFile(fileExtension) {
  let contentType = '';
  switch (fileExtension) {
    case 'doc':
      contentType = 'application/msword';
      break;
    case 'docx':
      contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      break;
    case 'pdf':
      contentType = 'application/pdf';
      break;
    case 'txt':
      contentType = 'text/plain';
      break;
    // 添加其他类型的处理逻辑
    default:
      contentType = '';
      break;
  }
  return contentType;
}
